from sys import stderr
from django.shortcuts import redirect, render
from django.http import JsonResponse
import json
import os
# Create your views here.

def get_table():
    os.system("route >> table.bin")
    with open("table.bin","r") as f:
        file_str = f.read()
    os.remove("table.bin")
    table = file_str.split("\n")
    table.pop(0)
    table.pop(0)
    x=[]
    for t in table:
        y = t.split(" ")
        z=[]
        for j in range(len(y)):
            if y[j]!='':
                z.append(y[j])
        if len(z)!=0:
            z.pop(3)
            z.pop(4)
            z.pop(4)
            x.append(z)
    return x

def dv(new_table):
    local_table = get_table()
    for i in range(len(new_table)):
        new_table[i][3] = int(new_table[i][3])+1
    map={}
    for i in range(len(local_table)):
        map[local_table[i][0]] = i
    for new_row in new_table:
        if new_row[0] in map:
            row = local_table[map[new_row[0]]]
            if new_row[4]==row[4]:
                x=os.system("route add -net "+new_row[0]+" netmask "+new_row[2]+" gw "+new_row[1]+" metric "+new_row[3]+" dev "+new_row[4])
            else:
                if int(new_row[3])<int(row[3]):
                    x=os.system("route del -net "+row[0]+" netmask "+row[2]+" gw "+row[1]+" metric "+row[3]+" dev "+row[4])
                    x=os.system("route add -net "+new_row[0]+" netmask "+new_row[2]+" gw "+new_row[1]+" metric "+new_row[3]+" dev "+new_row[4])
        else:
            x=os.system("route add -net "+new_row[0]+" netmask "+new_row[2]+" gw "+new_row[1]+" metric "+new_row[3]+" dev "+new_row[4])
    print(x)
    return x

def index(request):
    x=get_table()
    return render(request, "index.html",{"table":x})


def show_table(request):
    os.system("./getroute >> table.json")
    with open("table.json","r") as f:
        file_str = f.read()
        res = json.loads(file_str)
    os.remove("table.json")
    return JsonResponse(res)

def get_new_table(request):
    x = json.loads(request.body)
    dv(x["data"])
    return redirect("/")

def new_table(request):
    return render(request,"newtable.html")

def transport(request):
    return render(request,"transport.html")


def get_dest(requsest):
    x = json.loads(requsest.body) 
    buf=x["data"]
    res=[]
    for i in range(len(buf)):
        os.system("./transport "+buf[i]+" >> transport.bin")
        with open("transport.bin","r") as f:
            file = f.read()
            res.append(file)
        os.remove("transport.bin")
    return JsonResponse({"data":res})